package com.luoying.itew.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.luoying.itew.R;
import com.luoying.itew.activity.InformationActivity;
import com.luoying.itew.adapter.CollectAdapter;
import com.luoying.itew.bean.CollectData;
import com.luoying.itew.bean.CollectorBean;
import com.luoying.itew.dialog.CollectorDialog;
import com.luoying.itew.http.HttpRequestUtils;
import com.luoying.itew.http.HttpResponseCallBack;
import com.luoying.itew.util.LogUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 采集器界面
 * Created by Administrator on 2018/5/24.
 * time 2018-5-10
 * author zm
 */
public class CollectorFragment extends BaseFragment implements OnRefreshLoadMoreListener,CollectAdapter.CollectOnClickListener {
    private static final String TAG = "CollectorFragment";
    //延时刷新时间
    private static final int DELAYED_TIME = 600;
    //最大分页数
    private static final int MAX_LIMIIT = 7;

    @BindView(R.id.smartrefresh_layout)
    SmartRefreshLayout smartrefreshLayout;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    //监测id
    private String monitorId;
    //适配器
    private CollectAdapter adapter;
    //数据源
    private List<CollectorBean> list = new ArrayList<>();
    //页数
    private int pageno = 1;
    private boolean owner_gnss = false;

    @Override
    protected int getLayoutResId() {
        monitorId = ((InformationActivity) getActivity()).getCuurMonitorId() + "";
        return R.layout.collect_fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LogUtils.e(TAG, "onViewCreated: " );
    }

    @Override
    protected void init() {
        super.init();
        LogUtils.e(TAG, "init: "+getClass() );
        smartrefreshLayout.setOnRefreshLoadMoreListener(this);
        initGnssState();
        getList();
    }

    /**
     * 判断是否存在gnss采集器
     */
    public void  initGnssState(){
        //这里分页传了很大的值，目的获取所有采集器 判断有无gnss
        HttpRequestUtils.getInstance().collectionList(monitorId,1,Integer.MAX_VALUE, new HttpResponseCallBack<JsonObject>() {
            @Override
            public void onFail(String message) {

            }

            @Override
            public void onSuccess(JsonObject data) {
                if(data==null){
                    return;
                }
                try {
                    Gson gson = new Gson();
                    JsonArray array = data.getAsJsonObject("pagination").getAsJsonArray("records");
                    List<CollectorBean> beanList = gson.fromJson(array,new TypeToken<List<CollectorBean>>(){}.getType());
                    if(beanList==null){
                        return;
                    }
                    for (CollectorBean collectorBean : beanList) {
                        //如果有gnss采集器 设置为true 结束循环
                        if(collectorBean.getCollectorType()==0){
                            owner_gnss = true;
                            break;
                        }
                    }
                } catch (Exception e){
                    LogUtils.e(e.getMessage());
                }
            }

            @Override
            public void onError(String message) {

            }
        });
    }

    /**
     * 获取采集器列表
     */
    public void getList() {
        HttpRequestUtils.getInstance().collectionList(monitorId,pageno,MAX_LIMIIT, new HttpResponseCallBack<JsonObject>() {
            @Override
            public void onFail(String message) {
                smartrefreshLayout.finishRefresh(DELAYED_TIME,false);
                smartrefreshLayout.finishLoadMore(DELAYED_TIME);
            }

            @Override
            public void onSuccess(JsonObject data) {
                smartrefreshLayout.finishRefresh(DELAYED_TIME,true);
                smartrefreshLayout.finishLoadMore(DELAYED_TIME);
                if(data==null){
                    return;
                }
                try {
                    Gson gson = new Gson();
                    JsonArray array = data.getAsJsonObject("pagination").getAsJsonArray("records");
                    List<CollectorBean> beanList = gson.fromJson(array,new TypeToken<List<CollectorBean>>(){}.getType());
                    if(beanList==null){
                        return;
                    }
                    if(pageno==1){
                        smartrefreshLayout.setEnableLoadMore(true);
                        list.clear();
                    }
                    if(beanList.size()<MAX_LIMIIT){
                        smartrefreshLayout.setEnableLoadMore(false);
                    }
                    list.addAll(beanList);
                    setRecycleView();
                } catch (Exception e){
                    LogUtils.e(e.getMessage());
                }
            }

            @Override
            public void onError(String message) {
                smartrefreshLayout.finishRefresh(DELAYED_TIME,true);
                smartrefreshLayout.finishLoadMore(DELAYED_TIME);
            }
        });
        getCollectorList();

    }
    /**
     * 3d模型的采集器数据
     */
    public void getCollectorList() {

        List<CollectorBean> collectBeans = new ArrayList<>();
        HttpRequestUtils.getInstance().getCollectorList(Integer.valueOf(monitorId) , new HttpResponseCallBack<JsonObject>() {
            @Override
            public void onFail(String message) {
                Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onSuccess(JsonObject data) {
                try {
                    JsonArray  jsonElements = data.getAsJsonArray("collectorDatas");
                    List<CollectData> collectDataList = new Gson().fromJson(jsonElements.toString(),new TypeToken<List<CollectData>>(){}.getType());

//                    for (CollectorBean collectBean : collectBeans) {
//                        hashMap.put(collectBean.getCollectorId(),collectBean);
//                    }
//                    for (CollectData collectData : collectDataList) {
//                        if(hashMap.containsKey(Integer.valueOf(collectData.getCollectorId()))){
//                            MonitorUtils.bindColletrDate(hashMap.get(Integer.valueOf(collectData.getCollectorId())),collectData);
//                        }
//                    }
//                    Intent intent = new Intent(getActivity(), ModelActivity.class);
//                    getContext().startActivity(intent);
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String message) {
                Toast.makeText(getContext(), "网络连接错误", Toast.LENGTH_LONG).show();
            }
        });
    }


    private void setRecycleView() {
        adapter = new CollectAdapter(list,getContext());
        adapter.setListener(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        if (recyclerView == null) {
            return;
        }
        if (linearLayoutManager != null) {
            recyclerView.setLayoutManager(linearLayoutManager);
        }
        if (adapter != null) {
            recyclerView.setAdapter(adapter);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        pageno++;
        getList();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageno = 1;
        getList();
    }

    /**
     * 列表点击事件
     * @param bean
     */
    @Override
    public void onClick(CollectorBean bean) {
        if(bean==null){
            return;
        }
        CollectorDialog dialog = new CollectorDialog(getContext(), bean);
        dialog.owner_gnss = owner_gnss;
        dialog.show();
    }
}
